<script setup>

import { useRoute,useRouter } from 'vue-router';
import { ElMessage,ElMessageBox  } from 'element-plus';
import { merchantManagementList,StoreManagementList } from '@/api/BussinessMenage/index.js';
import { getReportList,getReportCount  } from '@/api/EngageManagement/financeAdministrate.js'
import { paymentSetupList } from '@/api/BusinessScope/paymentSetup'
import { exportFile } from '@/utils/common.js';
import { GMTToStr } from '@/utils/common.js'
const seachTable = ref(null);
const route = useRoute();
const router = useRouter();
const searchData = ref({})
//日期选择器暂存的时间日期，限制范围使用
const checkDateRange = ref([])

const formInline = ref([
    {
        type: "select",
        placeholder: "门店",
        label: '',
        prop: 'storeId',
        filterable: true,
        data:[],
        model: "",
        width:260
    },
    {
        type: "select",
        placeholder: "请选择趋势",
        label: '',
        clearable:false,
        prop: 'monthOrDay',
        data:[
            {
                label:"日趋势",
                value:0
            },
            {
                label:"月趋势",
                value:1
            }
        ],
        model: 0,
        handleChange:()=>{
            if(formInline.value[1].model == 0){
                formInline.value[2].model = [];
                formInline.value[2].type = "datePicker";
                formInline.value[2].disabled = false; 
                _setDefalutDate();
            }else if(formInline.value[1].model == 1){
                formInline.value[2].model = [];
                formInline.value[2].type = "monthPicker";
                formInline.value[2].disabled = false; 
                _setDefalutDate();
            }else{
                formInline.value[2].model = [];
                formInline.value[2].disabled = true; 
            }

        }
    },
    {
      type: "datePicker",
      prop: ["startTime", "endTime"],
      startPlaceholder: "开始时间",
      endPlaceholder: "结束时间",
      format:"YYYY-MM-DD",
      label: "",
      clearable:false,
      disabled:false,
      model:["",""],
      editDateValue:(value)=>{
        checkDateRange.value = [];
      },
      changeDateValue:(value)=>{
        checkDateRange.value = value;
      },
      disabledDate:(time)=>{
        let dateRange = checkDateRange.value;
        if((dateRange[0]??'') === ''){
          return false;
        }
        let startTimeValue = new Date(dateRange[0]).getTime();
        let endTimeValue = new Date(dateRange[0]);
        endTimeValue.setFullYear(endTimeValue.getFullYear() + 1);
        endTimeValue = endTimeValue.getTime();
        return time.getTime() < startTimeValue || time.getTime() > endTimeValue;
      }
    },
])
const _setDefalutDate = ()=>{
  let nowDate = new Date();  
  let startDate = nowDate.valueOf() - 30 * 24 * 3600 * 1000;
  startDate = GMTToStr(startDate);
  let endDate = nowDate;
  endDate = GMTToStr(endDate);
  formInline.value[2].model = [startDate,endDate];;
}
_setDefalutDate();
const btnLefts = ref([
{
        label:"导出",
        plain:false,
        type:"primary",
        show:true,
        plain:true,
        img:new URL("@/assets/icon/btn-export.png",import.meta.url),
        style:"border-color:#0C268C;color:#0C268C", 
        click:async ()=>{
            const loading = ElLoading.service({
                lock: true,
                text: '导出中',
                background: 'rgba(255, 255, 255, 0.7)',
            })
            
            try{
              await exportFile(`/jy-business/report/revenue/export`,'post',`门店经营报表`,{},{...searchData.value,type:1})
              loading.close()
            }catch(e){
              console.log(e,555232);
              loading.close()
            }
        }
    },

])
const btnRights = ref([

])

const tableConfig = ref([
    {
      prop: "storeName",
      label: "门店名称",

    },
    {
      prop: "computeTime",
      label: "日期",

    },
    {
      prop: "summaryPrice",
      label: "营收总额",
      type:"slot",
      slotName:'ysze',

    },
    {
      prop: "summary",
      label: "汇总",
      type:"child",
      headerAlign:"center",
      children:[
        {
            prop: "summaryProduct",
            label: "产品营收",
            needHeader:true,
            slotHeaderName:"cpyshz",
            width:120
        },
        {
            prop: "summaryProject",
            label: "项目营收",
            slotHeaderName:"xxyshz",
            needHeader:true,
            width:120
        },
      ]
    },
    {
      prop: "detail",
      label: "明细",
      type:"child",
      headerAlign:"center",
      className:"no-right",
      children:[
        {
            prop: "detailCombo",
            label: "套餐营收",
            width:120
        },
        {
            prop: "detailCourse",
            label: "疗程营收",
            width:120
        },
        {
            prop: "detailProduct",
            label: "产品营收",
            slotHeaderName:"cpysmx",
            needHeader:true,
            width:120
        },
        {
            prop: "detailProject",
            label: "项目营收",
            slotHeaderName:"xxysmx",
            needHeader:true,
            width:120
        },
      ]
    },
]);
const tableLoading = ref(false)
const totalPage = ref(0)
const tableData = ref([]);
const payData = ref([]);
const totalValue = ref({
    countRevenue:0,
    countProject:0,
    countProduct:0
})
const _paymentSetupList = async ()=>{
    const res = await paymentSetupList({page:{size:99999,current:1}});

    payData.value = res;
}

const handlerSearch = async (formInline)=>{
    tableLoading.value = true;
    try{
        let data = {
          ...formInline,
        }
        if(data.monthOrDay == 0){
            if((data.startTime??'') !== ''){
                data.startTime =data.startTime.split(" ")[0]; 
            }
            if((data.endTime??'') !== ''){
                data.endTime =data.endTime.split(" ")[0]; 
            }
        }else if(data.monthOrDay == 1){
            if((data.startTime??'') !== ''){
                let startTime =data.startTime.split(" ")[0]; 
                startTime = startTime.split("-");
                data.startTime = [startTime[0],startTime[1]].join("-")
            }
            if((data.endTime??'') !== ''){
                let endTime =data.endTime.split(" ")[0]; 
                endTime = endTime.split("-");
                data.endTime = [endTime[0],endTime[1]].join("-")
            }
        }
        searchData.value = data
        await _paymentSetupList();
        const totalRes = await getReportCount(data);
        totalValue.value.countRevenue = totalRes && totalRes.countRevenue?totalRes.countRevenue:0;
        totalValue.value.countProject = totalRes && totalRes.countProject?totalRes.countProject:0;
        totalValue.value.countProduct = totalRes && totalRes.countProduct?totalRes.countProduct:0;
        const res = await getReportList(data);

        totalPage.value = Number(res.total)
        tableData.value = res.records
    }catch(e){
       console.log(e,222)
    }finally{
        tableLoading.value = false;
    }
}
// 获取门店列表
const _getStoreManagementList = async ()=>{
  let result = await StoreManagementList({page:{size: 10000, current: 1}});
  formInline.value[0].data = result.records.map(lis=>{
    return {
      label:lis.storeName,
      value:lis.id
    }
  });
}
const setPayWayName = (val)=>{
    if((val??'') === ''){
        return '未知'
    }

    let payName = "";

    payData.value.forEach(lis=>{
        if(lis.id == val){
            payName = lis.configValue
        }
    })
    if(val == '1818'){
        payName = '九养云支付';
    }
    return payName;
    
}
onMounted(()=>{
    _getStoreManagementList();
})




</script>
<template>
    <div class="page-content">
        <SeachTable 
          :tableType="1"
          ref="seachTable"
          :forms="formInline"
          :btnLefts="btnLefts"
          :btnRights="btnRights"
          :tableLoading="tableLoading"
          :tableConfig="tableConfig"
          :tableData="tableData"
          :isAdditional="true"
          :totalPage="totalPage"
          @handlerSearch="handlerSearch"
          :isReset="false"
        >
            <template #additional>
                <div class="data-block">
                    <div class="lis-block">
                        <span class="lable-name">
                            营收总额：
                        </span>
                        <span class="price">
                            ¥{{ totalValue.countRevenue || 0 }}
                        </span>
                    </div>
                    <div class="lis-block">
                        <span class="lable-name">
                            产品营收：
                        </span>
                        <span class="price">
                            ¥{{ totalValue.countProduct || 0 }}
                        </span>
                    </div>
                    <div class="lis-block">
                        <span class="lable-name">
                            项目营收：
                        </span>
                        <span class="price">
                            ¥{{ totalValue.countProject || 0 }}
                        </span>
                    </div>

                </div>
            </template>
            <template #cpyshz>
                <div class="info-show">
                    <div class="text-show" style="font-size: 14px;font-weight: bold;color: #313233;">
                        产品营收
                    </div>
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                                所有产品（包括套餐和疗程中的）营收
                            </div>
                        </template>
                        <img src="@/assets/images/warning-circle.png" alt="" class="img">
                    </el-tooltip>

                </div>
            </template>
            <template #xxyshz>
                <div class="info-show">
                    <div class="text-show" style="font-size: 14px;font-weight: bold;color: #313233;">
                        项目营收
                    </div>
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                                所有项目（包括套餐和疗程中的）营收
                            </div>
                        </template>
                        <img src="@/assets/images/warning-circle.png" alt="" class="img">
                    </el-tooltip>

                </div>
            </template>
            <template #cpysmx>
                <div class="info-show">
                    <div class="text-show" style="font-size: 14px;font-weight: bold;color: #313233;">
                        产品营收
                    </div>
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                                套餐和疗程以外的产品营收
                            </div>
                        </template>
                        <img src="@/assets/images/warning-circle.png" alt="" class="img">
                    </el-tooltip>

                </div>
            </template>
            <template #xxysmx>
                <div class="info-show">
                    <div class="text-show" style="font-size: 14px;font-weight: bold;color: #313233;">
                        项目营收
                    </div>
                    <el-tooltip placement="top">
                        <template #content>
                            <div class="tips-info">
                                套餐和疗程以外的项目营收
                            </div>
                        </template>
                        <img src="@/assets/images/warning-circle.png" alt="" class="img">
                    </el-tooltip>

                </div>
            </template>
            <template #ysze="{ row }">
                <div style="display: flex;justify-content:flex-start;align-items:center">
                    {{ row.summaryPrice }}
                    <el-popover
                        placement="bottom"
                        trigger="hover"
                        :width="140"
                        
                    >
                        <div class="show-tips">
                            <div class="in-line" v-for="(item,index) in row.payDetail" :key="index">
                                <span style="margin-right:4px">{{ setPayWayName(item.payWayId) }}</span>
                                <span>{{ item.payAmount }}</span>
                            </div>
                        </div>
                        <template #reference>

                            <div class="price-show">
                                <img src="@/assets/images/zbt.png" alt="" v-if="row.payDetail && row.payDetail.length>0">
                            </div>
                        </template>
                    </el-popover>
                </div>
            </template>
        </SeachTable>
    </div>
</template>


<style lang="less" scoped>
.price-show{
    margin-left:4px;

    img{
        width: 14px;
        height: 14px;
        position: relative;
        top:3px;
        cursor: pointer;
    }
}
.show-tips{
  width: 100%;
  .in-line{
    width: 100%;
    margin-bottom:12px;
    color:#222222;
    font-size: 14px;

    &:last-child{
        margin-bottom:0px;

    }
  }
}
.tips-info{
    max-width: 300px; 
}
.info-show{
    width: 100%;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    .text-show{
        max-width: calc(100% - 14px);
        box-sizing:border-box;
        padding-right:4px;
        font-weight: 400;
        color: #222222;
        line-height: 18px;
        word-break: break-all;
        word-wrap: break-word;
        
    }
    .img{
        width: 14px;
        height: 14px;
        cursor: pointer;

    }
}
.data-block{
    width: 100%;

    border-radius: 4px;
    background: linear-gradient(0deg, #ff6b001a 0%, #ff6b001a 100%), #FFF;

    padding:0 12px;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    box-sizing: border-box;
    height: 42px;
    .lis-block{
        margin-right: 40px;
        display: flex;
        justify-content: flex-start;

        .lable-name{
            font-weight: bold;
            color: #000000;
            font-size: 14px;

        }
        .price{
            font-weight: bold;
            color: #FF6B00;
            font-size: 18px;

        }
    }
}
</style>
